// pages/address/list/list.js
import request from '../../../utils/request'
import Dialog from '@vant/weapp/dialog/dialog';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    address: null,
    showbtn: 0
  },
  // 地址选中
  handeItemChange(e) {
    // 1 获取被修改的商品的id
    const id = e.currentTarget.dataset.id;
    // 2 获取购物车数组 
    let address = this.data.address;
    // 3 找到被修改的商品对象
    let index = address.findIndex(v => v.id === id);
    // 4 选中状态取反
    address[index].checked = !address[index].checked;
    console.log(address)
    this.setData({
      address: address
    })

  },
  // 选择地址
  selectAddress() {
    let arr = []
    this.data.address.map(item => {
      if (item.checked) {
        arr.push(item)
      }
    })
    console.log(arr)
    if (arr.length == 1) {
      wx.setStorageSync("address", arr);
      if (this.data.showbtn == 1) {
        wx.switchTab({
          url: '/pages/tabbar/cart/cart',
        })
      } else if (this.data.showbtn == 2) {
        wx.navigateTo({
          url: '/pages/tabbar/cart/cart',
        })
      }

    } else {
      wx.showToast({
        title: '请选择一个收货地址',
        icon: 'none',
      });
    }
  },
  addAddress() {
    wx.navigateTo({
      url: '/pages/address/add/add',
    })
  },
  editAddress(event) {
    wx.navigateTo({
      url: '/pages/address/edit/edit?id=' + event.currentTarget.id,
    })
  },
  deleteAddress(event) {
    let _this = this;
    Dialog.confirm({
      message: '确定删除吗？',
    }).then(() => {
      _this.delete(event);
      _this.onShow();
    });
  },
  async delete(event) {
    let res = await request.get('/address/delete', { id: event.currentTarget.id })
    if (res.data.code === 200) {
      // wx.navigateTo({
      //   url: '/pages/address/list/list',
      // })
    }
  },
  onChange(event) {
    // event.detail 为当前输入的值
    console.log(event.detail);
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options.showbtn)
    this.setData({ showbtn: options.showbtn })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: async function () {
    let res = await request.get('/address/list', { userId: 100030 })
    res.data.data.map(item => {
      item.checked = false
    })
    console.log(res.data.data)
    this.setData({
      address: res.data.data
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})